import requests
import json
import pandas as pd
import requests
import json
import datetime
import time


# data = "{\"flightWay\":\"Oneway\",\"classType\":\"ALL\",\"hasChild\":false,\"hasBaby\":false,\"searchIndex\":1,\"portingToken\":\"5dd660535eba4918910e6c2a4ed684fe\",\"airportParams\":[{\"dcity\":\"bjs\",\"acity\":\"sha\",\"dcityname\":\"北京\",\"acityname\":\"上海\",\"date\":\"2018-07-25\"}]}".encode('utf-8')
headers = json.loads(r'''{
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Length": "249",
    "Content-Type": "application/json",
    "Cookie": "_abtest_userid=8acd19cf-eed4-4003-9798-09b853ecea23; MKT_Pagesource=PC; _RSG=rEaiXomkHlFcTT8sROMRn9; _RDG=2894910ed9557729900c27b931efc61941; _RGUID=fbd1bb0c-a1b2-43b5-9c5b-5986f621d766; _fpacid=09031046311358487592; GUID=09031046311358487592; traceExt=campaign=CHNbaidu81&adid=index; _RF1=36.27.5.185; _jzqco=%7C%7C%7C%7C%7C1.1483656233.1531962586386.1532324690294.1532324697770.1532324690294.1532324697770.0.0.0.19.19; __zpspc=9.6.1532324690.1532324697.2%231%7Cbaidu%7Ccpc%7Cbaidu81%7C%25E6%2590%25BA%25E7%25A8%258B%7C%23; cticket=B2C46C186810D97621A00F12F5F3CB4EC84251572DBF34AA579A9EF2DEDF8037; DUID=u=A0D63949572832465A998732AE73AFBB&v=0; IsNonUser=F; ticket_ctrip=uoeOwviAJ6VQEgTNwLuTqSV9j/bS+aOP3Riia1P+kyQbgkQZsD2gibEbkYhyWHIdCcaIzFcoGyvpZI5x4SEYsualULDiWxVQi6fbNceaIjNacVL4y5tBHRGAq+ECIk5GxRb/7vfILeV+2uOCd5XTCP+feU2ylAi7FQ86WuGvLX50brVPdbdBEs7egpaOrZTRYAXOOrIrJeBleS3hWq+70ETGWg3Y4hPZQksQs7b4AhZTad+a/GnjUC+uaMgxdafWFeVaDWVAwKjNpMpvnddqhRdACe4Yl3CoglCNk+dzN2f3LNeexDAy9hIAtIXEsdox; corpid=; corpname=; CtripUserInfo=VipGrade=0&UserName=&NoReadMessageCount=0&U=391E96138E606383B50FFBD1E20AF349; AHeadUserInfo=VipGrade=0&UserName=&NoReadMessageCount=0&U=391E96138E606383B50FFBD1E20AF349; LoginStatus=1%7c; Union=AllianceID=1881&SID=2209&OUID=0ACAE5E9EEC9C0CAFE36B60E37D966F3%7c100.1030.00.000.00; Session=SmartLinkCode=U2209&SmartLinkKeyWord=&SmartLinkQuary=&SmartLinkHost=&SmartLinkLanguage=zh; FD_SearchHistorty={\"type\":\"S\",\"data\":\"S%24%u5317%u4EAC%28BJS%29%24BJS%242018-07-24%24%u4E0A%u6D77%28SHA%29%24SHA\"}; ASP.NET_SessionId=lhhn3pxipbpmmwdaag5iverb; TraceSession=1383495446; ASP.NET_SessionSvc=MTAuMTUuMTI4LjI1fDkwOTB8b3V5YW5nfHwxNTI2NTQ4NjU0Nzg3; _bfa=1.1531962577671.27djnt.1.1532047811172.1532324682000.5.49.10320605175; _bfs=1.4; Mkt_UnionRecord=%5B%7B%22aid%22%3A%224897%22%2C%22timestamp%22%3A1532324697739%7D%2C%7B%22aid%22%3A%221881%22%2C%22timestamp%22%3A1532324729164%7D%5D",
    "Host": "flights.ctrip.com",
    "Origin": "http://flights.ctrip.com",
    "Referer": "http://flights.ctrip.com/itinerary/oneway/bjs-sha?date=2018-07-25&portingToken=5dd660535eba4918910e6c2a4ed684fe",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}''')

    
# aa = {"dcity":"bjs","acity":"sha","dcityname":"北京","acityname":"上海","date":"2018-07-23"}
# cc = {"flightWay":"Oneway","classType":"ALL","hasChild":"false","hasBaby":"false","searchIndex":"1","portingToken":"9715c4aece8c4647af3bccd63b15a843","airportParams":[aa]}
# data = json.dumps(cc)
# resp = requests.post(url, data=data, headers=headers)
# # print(resp.text)
# with open('a.json','w',encoding='utf-8') as f:
#     f.write(resp.text)

datacol = {0:'爬虫时间',1:'当前日期',2:'始发地',3:'目的地',4:'出发时点',5:'到达时点',6:'航班',7:'航班公司',8:'飞机型号',9:'起飞机场',10:'降落机场',11:'准点率',12:'是否直飞'}

class xiecheng():

    def __init__(self):
        self.mylist = []
        self.main_url = "http://flights.ctrip.com/itinerary/api/12808/products"

    def getContent(self,times):  
        print(f'正在获取{times}')
        aa = {"dcity":"bjs","acity":"sha","dcityname":"北京","acityname":"上海","date":times}
        cc = {"flightWay":"Oneway","classType":"ALL","hasChild":"false","hasBaby":"false","searchIndex":"1","portingToken":"5dd660535eba4918910e6c2a4ed684fe","airportParams":[aa]}
        data = json.dumps(cc)
        resp = requests.post(self.main_url, data=data, headers=headers)  
        if resp:
            myjson = json.loads(resp.text)
            routeList = myjson['data']['routeList']
            for fj in routeList:
                if fj['routeType'] == 'Flight':
                    flight = fj['legs'][0]['flight']

                    scity = '北京'
                    ecity = '上海'
                    stime = flight['departureDate']
                    etime = flight['arrivalDate']
                    countyName = flight['airlineName']
                    no = flight['flightNumber']
                    fjxh = flight['craftTypeName']
                    sjc = flight['arrivalAirportInfo']['airportName']
                    ejc = flight['departureAirportInfo']['airportName']
                    zdl = flight['comfort']
                    if 'HistoryPunctualityArr' in zdl:
                        zdl = zdl.split('HistoryPunctualityArr":"')[1].split('"')[0]
                    list1= [time.strftime("%Y/%m/%d - %H:%M:%S"),times,scity,ecity,stime,etime,no,countyName,fjxh,sjc,ejc,zdl]
                    if flight['stopInfo']:
                        list1.append('不是直飞')
                    else:
                        list1.append('直飞')
                if 'cabins' in fj['legs'][0]:
                    for place in fj['legs'][0]['cabins']:
                        types = {'Y':'经济舱','C':'公务舱','F':'头等舱'}
                        tp = place['refundEndorse']['refundNote']
                        gq = place['refundEndorse']['changeNote']
                        fj_str =place['cabinClass']  + str(types[place['cabinClass']]) + "    "+str(place['price']['salePrice']) + "   " + str(place['price']['rate']) + '\n' + str(tp) + '\n' + str(gq)
                        list1.append(fj_str)
                self.mylist.append(list1)


    def start(self):
        try:
            now = datetime.datetime.now()
            for i in range(0,60):
                delta = datetime.timedelta(days=i)
                n_days = now + delta
                self.getContent(n_days.strftime('%Y-%m-%d'))
            # print(self.mylist)
            df = pd.DataFrame(self.mylist)
            df.rename(columns=datacol,inplace=True)
            df.to_excel('机票数据7.xlsx')
        except Exception as e:
            df = pd.DataFrame(self.mylist)
            df.rename(columns=datacol,inplace=True)
            df.to_excel('机票数据7.xlsx')
            raise
        # now = datetime.datetime.now()
        # for i in range(0,300):
        #     delta = datetime.timedelta(days=i)
        #     n_days = now + delta
        #     self.getContent(n_days.strftime('%Y-%m-%d'))
        # # print(self.mylist)
        # df = pd.DataFrame(self.mylist)
        # df.rename(columns=datacol,inplace=True)
        # df.to_excel('demo.xlsx')



if __name__ == '__main__':
    xiecheng().start()